/**
 * 分步表单示例
 */
import React, { useState, useEffect, useMemo } from 'react';
import { Card, Steps } from 'choerodon-ui';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import { connect } from 'dva';
import { DataSet } from 'choerodon-ui/pro';
import { StateType } from './model';
import Step1 from './components/Step1';
import Step2 from './components/Step2';
import Step3 from './components/Step3';
import getFormDS from './formDataSet';

const { Step } = Steps;

interface StepFormProps {
  current: StateType['current'];
}

/**
 * 分步表单：
 * 当前对应的步骤保存于状态树
 * 如果需要跳转步骤，则更新状态树中对应的状态
 */
const StepForm: React.FC<StepFormProps> = ({ current }) => {
  const dataSet = useMemo(() => new DataSet(getFormDS()), []);
  const [stepComponent, setStepComponent] = useState<React.ReactNode>(null);
  const [currentStep, setCurrentStep] = useState<number>(0);

  const getCurrentStepAndComponent = (_current?: string) => {
    switch (_current) {
      case 'confirm':
        return { step: 1, component: <Step2 dataSet={dataSet} /> };
      case 'result':
        return { step: 2, component: <Step3 dataSet={dataSet} /> };
      case 'info':
      default:
        return { step: 0, component: <Step1 dataSet={dataSet} /> };
    }
  };
  // 状态树中的当前步骤发生变化时，设置显示组件和当前步骤
  useEffect(() => {
    const { step, component } = getCurrentStepAndComponent(current);
    setCurrentStep(step);
    setStepComponent(component);
  }, [current]);

  return (
    <PageHeaderWrapper title="将一个冗长或用户不熟悉的表单任务分成多个步骤，指导用户完成。">
      <Card bordered={false}>
        <>
          <Steps current={currentStep}>
            <Step title="填写转账信息" />
            <Step title="确认转账信息" />
            <Step title="完成" />
          </Steps>
          {stepComponent}
        </>
      </Card>
    </PageHeaderWrapper>
  );
};

export default connect(({ stepForm }: { stepForm: StateType }) => ({
  current: stepForm.current,
}))(StepForm);
